<template>
  <div class="app-container">
    <!-- 生产单档案 -->

    <div class="search-bar">
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="生产单号" prop="batch">
          <el-input
            v-noSpace
            v-model="queryParams.batch"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
            placeholder="请输入生产单号"
          />
        </el-form-item>

        <el-form-item label="产品名称" prop="productCode">
          <el-select
            v-model="queryParams.productCode"
            placeholder="请选择产品名称"
            class="!w-[192px]"
            clearable
            filterable
            @visible-change="getProductType"
            @change="handleQuery"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料名称" prop="sourceCode">
          <el-select
            v-model="queryParams.sourceCode"
            placeholder="请选择原材料名称"
            class="!w-[192px]"
            clearable
            filterable
            @visible-change="getProduct"
            @change="handleQuery"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="移库状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择移库状态"
            class="!w-[192px]"
            clearable
            @change="handleQuery"
          >
            <el-option label="待移库" :value="0" />
            <el-option label="移库中" :value="1" />
            <el-option label="移库完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="移库单号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
            placeholder="请输入移库单号"
          />
        </el-form-item>

        <el-form-item label="生产日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="daterange"
            placeholder="选择日期"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            value-format="YYYY-MM-DD"
            picker-options="pickerOptions"
            @change="handleQuery"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">查询</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 生产单列表 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="pageData"
        show-overflow-tooltip
        max-height="250px"
        @row-click="handleProdQuery"
      >
        <el-table-column prop="code" label="移库单号" min-width="100" />
        <el-table-column prop="batch" label="生产单号" min-width="100" />
        <el-table-column prop="productName" label="生产产品" />
        <el-table-column prop="prodDate" label="生产日期">
          <template #default="scope">
            {{ scope.row.prodDate || "-" }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="移库状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">待移库</el-tag>
            <el-tag v-if="scope.row.status == 1" type="info">移库中</el-tag>
            <el-tag v-if="scope.row.status == 2" type="success">移库完成</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="moveDate" label="移库完成日期">
          <template #default="scope">
            {{ scope.row.moveDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <el-button
              v-hasPerm="'sys:stockPreparation:force'"
              v-if="scope.row.status == 0 || scope.row.status == 1"
              link
              type="warning"
              size="small"
              @click="handleDetail(scope.row)"
            >
              强制完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-card shadow="never" class="mt-4">
      <el-table :data="tableData" show-overflow-tooltip>
        <el-table-column prop="productCode" label="原材料编号" />
        <el-table-column prop="productName" label="原材料名称" />
        <el-table-column label="待移库数量">
          <template #default="scope">
            {{ scope.row.totalQty - (scope.row.moveQty || 0) }}{{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="moveQty" label="已移库数量">
          <template #default="scope">
            {{ scope.row.moveQty || 0 }}{{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalQty" label="总移库数量">
          <template #default="scope">
            {{ scope.row.totalQty || 0 }}{{ unitFormat(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-card>
    <pagination
      v-if="prodTotal > 0"
      v-model:total="prodTotal"
      v-model:page="queryProdTotalParams.pageNum"
      v-model:limit="queryProdTotalParams.pageSize"
      @pagination="handleProdQuery"
    />
  </div>
</template>

<script setup lang="ts">
import materialQueryApi, {
  materialQueryPageVO,
  materialQueryPageQuery,
} from "@/api/prodManage/materialQuery";
import configApi, { ConfigType } from "@/api/config/config";

import productBomAPI from "@/api/productBom/productBom";
const materialFormRef = ref(ElForm);

const tableData = ref([]);

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getProductType = async () => {
  try {
    const response = await productBomAPI.getTypePage({
      pageNum: 1,
      pageSize: 20,
      productType: "1",
    });
    const dataList = response?.list || [];

    options.value = dataList.map((item: any) => ({
      value: item.code,
      label: item.productName,
    }));
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};

//原材料
const productOptions = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getProduct = () => {
  productBomAPI
    .getTypePage({ pageNum: 1, pageSize: 20, productType: "2" })
    .then((data) => {
      productOptions.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

const queryFormRef = ref(ElForm);

const queryParams = reactive<materialQueryPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<materialQueryPageVO[]>();

const total = ref(0);
const loading = ref(false);

// 新增/修改form
const dialogFormData = reactive<materialQueryPageVO>({ moveQty: 0 });

const rules = reactive({});

// 查询
function handleQuery() {
  loading.value = true;
  console.log("queryParams", queryParams);
  materialQueryApi
    .getPage(queryParams)
    .then((data: any) => {
      pageData.value = [...(data.list as any)];
      console.log("data", data);
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

//强制完成
function handleDetail(row: any) {
  //是否确定
  ElMessageBox.confirm("是否确定强制完成?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      materialQueryApi.forceComplete(row.id).then(() => {
        ElMessage.success("操作成功");
        handleQuery();
      });
    })
    .catch(() => {});
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;

  handleQuery();
}

//查询子集
const queryProdTotalParams = reactive<materialQueryPageQuery>({
  pageNum: 1,
  pageSize: 20,
});
const prodTotal = ref(0);
const handleProdQuery = (row: any) => {
  materialQueryApi.getDetail(row.code).then((data) => {
    tableData.value = data;
  });
};
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

onMounted(() => {
  handleQuery();
  getUnitList();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
